package com.demo.aop;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.demo.core.exception.ParameterException;
import com.demo.utils.Token;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class AuthorizationAspect {

    @Pointcut("@annotation(com.demo.aop.AuthorizationRequired)")
    public void authorizationRequired() {}

    @Around("authorizationRequired()")
    public Object getUserIdAndAuthorize(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (token == null || token.equals("")) {
            throw new ParameterException("token为空");
        }
        Long uid;
        DecodedJWT verify = Token.verify(token);//解密账号
        uid = verify.getClaim("uid").asLong();//将解密得到的账号信息存到userid中
        if (uid == null) {
            throw new ParameterException("用户未认证");
        }
        // 将用户ID存入request中
        request.setAttribute("userId", uid);
        // 继续执行目标方法
        return joinPoint.proceed();
    }
}
